/*  header-comment
/*  file   : /Users/jessica/react-hrm-h5/src/modules/onJobList/index
/*  author : Allan
/*  date   : 2017-09-09 23:17
/*  last   : 2017-11-4 20:16:49
*/
import React, { Component } from "react";
import PropTypes from "prop-types";
import { bindActionCreators } from "redux";
import { connect } from "react-redux";
import { List, RefreshControl, Icon as DIcon } from "@ali/ding-ui";
import autobind from "autobind-decorator";
import { getLists } from "../../actions/onJobList/";
import { getProbationList, getDismissionList } from "../../actions/onJobList/";

import "./index.less";
import { mid2Url } from "@ali/ding-mediaid";

// componet
import DDAvatar from "../../components/Avatar/";
import Filter from "./filter";
import { setTitle, setRight, openLink, alert } from "../../utils/dingtalk.js";
import Icon from "../../components/Icon";
import ListView from "../../components/perfectListView";
import urlParams from "../../utils/urlParams";
//utils
import { set, get, remove } from "../../utils/sessionDb.js";

const mapper = {
	"1": "待入职",
	"2": "试用期",
	"3": "正式",
	"4": "已离职",
	"5": "待离职"
};

const Item = List.Item;
const Brief = Item.Brief;
const PAGE_SIZE = 15;
const LIST_ONJOB = "onjob";
const LIST_PROBATION = "probation";
const LIST_DEPARTURE = "departure";

const mapStateToProps = () => ({});
const mapDispatchToProps = dispatch => ({
	actions: bindActionCreators(
		{
			dispatch,
			getLists,
			getProbationList,
			getDismissionList
		},
		dispatch
	)
});

@connect(mapStateToProps, mapDispatchToProps)
export default class OnJobList extends Component {
	static propTypes = {
		actions: PropTypes.shape({
			dispatch: PropTypes.func.isRequired,
			getLists: PropTypes.func.isRequired
		}).isRequired
	};
	constructor(props) {
		super(props);
		const dataSource = new ListView.DataSource({
			rowHasChanged: (row1, row2) => row1 !== row2
		});
		let currenList;
		if (
			this.props.location.query &&
			this.props.location.query.list == "probation"
		) {
			currenList = LIST_PROBATION;
		} else if (
			this.props.location.query &&
			this.props.location.query.list == "departure"
		) {
			currenList = LIST_DEPARTURE;
		} else {
			currenList = LIST_ONJOB;
		}

		this.state = {
			showFilter: true,
			dataSource,
			currenList: currenList,
			isLoading: true,
			refreshing: false,
			height: document.body.clientHeight,
			// 当前页码
			pageIndex: 1,
			hasMore: false,
			data: [],
			prePage: 1,
			total: "",
			//人数
			number: 0,
			fragmentCount: sessionStorage.getItem("fragmentCount")
				? sessionStorage.getItem("fragmentCount").split(",")
				: [],
		};

		//筛选条件 用于接口请求
		this.param = {};

		//筛选条件 用于标签显示文本
		this.paramText = {
			depts: [],
			employee: []
		};

		//无筛选器时列表表头没有margintop样式
		this.headerClass = "";
		this.initDb();

		setRight({
			show: false
		});
	}

	bindListener = () => {
		this.bindFunc = e => {
			//todo some function  but can‘t preventDefault event
			console.log(e);
		};
		document.querySelector("#filterContainer").addEventListener("touchmove", this.bindFunc);
		
		//在后续跳转到后面页面操作完成之后返回刷新
		window.needReload = () => { 
			this.setState(
				{
					dataSource: this.state.dataSource.cloneWithRows([]),
					isLoading: true,
					pageIndex: 1,
					hasMore: false,
					data: [],
					number: 0
				},
				() => {
					this.getLists(1);
				}
			);
		}
	};

	removeListener = () => {
		document
			.querySelector("#filterContainer")
			.removeEventListener("touchmove", this.bindFunc);
	};

	componentDidMount() {
		this.bindListener();
		if (this.state.currenList == LIST_PROBATION) {
			setTitle({ title: "试用期员工" });
		} else if (this.state.currenList == LIST_DEPARTURE) {
			setTitle({ title: "离职员工" });
		} else if (this.state.currenList == LIST_ONJOB) {
			// 加载页面时给一个默认的title
			setTitle({ title: "在职员工" });
		} else {
			setTitle({ title: "" });
		}
	}

	componentWillUnmount() {
		this.removeListener();
		this.clearFliterType();
	}
	/**
	 * 进入页面加载初始列表
	 **/
	componentWillMount() {
		if (this.state.currenList == LIST_PROBATION) {
			setTitle({ title: "试用期员工" });
		} else if (this.state.currenList == LIST_DEPARTURE) {
			setTitle({ title: "离职员工" });
		} else if (this.state.currenList == LIST_ONJOB) {
			// 加载页面时给一个默认的title
			setTitle({ title: "在职员工" });
		} else {
			setTitle({ title: "" });
		}

		let { deptsId = "", deptsName = "" } = this.props.location.query;
		if (deptsId !== "" && deptsName !== ""){
			let param = {
				depts: deptsId
			};
			let paramText = {
				depts: deptsName.split(",")
			}
			this.onFilter(param, paramText);
		}
		
		this.getLists(1);
	}

	initDb() {
		var func = function (key) {
			return JSON.parse(get(key));
		};
		if (func("onJobListFilterParam")) this.param = func("onJobListFilterParam");
		if (func("onJobListFilterParamText"))
			this.paramText = func("onJobListFilterParamText");
		// if(get("onJobListFilterParam")) this.param = JSON.parse(get("onJobListFilterParam"));
		// if(get("onJobListFilterParamText")) this.paramText = JSON.parse(get("onJobListFilterParamText"));
	}

	/**
	 * 获取列表
	 *
	 * @param {page: 页码, pageSize: 默认条数}
	 * */
	getLists = pageNum => {
		if (
			this.props.location.query &&
			this.props.location.query.list == "probation"
		) {
			this.headerClass = "no-mt";
			this.setState({
				showFilter: false
			});
			this.props.actions
				.getProbationList({
					page: pageNum,
					pageSize: PAGE_SIZE
				})
				.then(res => {
					const data = [...this.state.data, ...res.result.data];
					this.setState({
						dataSource: this.state.dataSource.cloneWithRows(data),
						hasMore: res.result.hasMore,
						isLoading: false,
						refreshing: false,
						total: res.result.total,
						data,
						number: res.result.totalSearchNo
					});

					setTitle({
						title: "试用期员工"
					});
				});
		} else if (
			this.props.location.query &&
			this.props.location.query.list == "departure"
		) {
			this.headerClass = "no-mt";
			this.setState({
				showFilter: false
			});
			this.props.actions
				.getDismissionList({
					page: pageNum,
					pageSize: PAGE_SIZE
				})
				.then(res => {
					const data = [...this.state.data, ...res.result.data];

					this.setState({
						dataSource: this.state.dataSource.cloneWithRows(data),
						hasMore: res.result.hasMore,
						isLoading: false,
						refreshing: false,
						total: res.result.total,
						data,
						number: res.result.total
					});

					setTitle({
						title: "离职员工"
					});
				});
		} else {
			this.headerClass = "";
			this.props.actions
				.getLists({
					page: pageNum,
					pageSize: PAGE_SIZE,
					...this.param
				})
				.then(res => {
					// console.log("获取新的数据");
					let data = [...this.state.data, ...res.result.data];
					this.setState({
						dataSource: this.state.dataSource.cloneWithRows(data),
						hasMore: res.result.hasMore,
						isLoading: false,
						refreshing: false,
						showFilter: true,
						total: res.result.total,
						data,
						number: res.result.totalSearchNo
					});
				});
		}
	};

	/**
	 * 下拉加载更多
	 * 该组件有坑～
	 * https://github.com/ant-design/ant-design-mobile/issues/520#issuecomment-263510596
	 * */
	onEndReached = () => {
		if (this.state.isLoading) {
			return;
		}
		if (!this.state.hasMore) {
			return;
		}
		const nextPage = this.state.pageIndex + 1;
		if (this.state.prePage !== nextPage) {
			this.state.prePage = nextPage;
			this.setState(
				{
					isLoading: true,
					pageIndex: nextPage,
					prePage: nextPage
				},
				() => {
					this.getLists(nextPage);
				}
			);
		}
	};

	/**
	 * 顶部下拉刷新页面(use html body as a scroll container.)
	 * */
	onRefresh = () => {
		console.log("onRefresh"); // eslint-disable-line
		this.setState({ refreshing: true });
		this.prePage = 1;
		this.setState(
			{
				dataSource: this.state.dataSource.cloneWithRows([]),
				isLoading: true,
				pageIndex: 1,
				hasMore: false,
				data: [],
				number: 0
			},
			() => {
				this.getLists(1);
			}
		);
	};

	/* 
	 * 根据筛选条件请求列表页面
	 */
	onFilter = (param, paramText) => {
		console.log(param, paramText)
		this.setState({
			dataSource: this.state.dataSource.cloneWithRows([])
		});
		this.setFilterType(param, paramText);
		this.props.actions
			.getLists({
				...this.param,
				page: 1,
				pageSize: PAGE_SIZE
			})
			.then(res => {
				const data = [...res.result.data];
				this.setState({
					dataSource: this.state.dataSource.cloneWithRows(data),
					hasMore: res.result.hasMore,
					isLoading: false,
					total: res.result.total,
					data,
					number: res.result.totalSearchNo
				});
			});
	};

	// 获取&更新缓存筛选条件
	getFilterType = () => {
		return [get("onJobListFilter::param"), get("onJobListFilter::paramText")];
	};
	setFilterType = (param, paramText) => {
		Object.assign(this.param, param);
		Object.assign(this.paramText, paramText);
		set("onJobListFilterParam", JSON.stringify(this.param));
		set("onJobListFilterParamText", JSON.stringify(this.paramText));
	};
	clearFliterType = () => {
		set("onJobListFilterParam", JSON.stringify(""));
		set("onJobListFilterParamText", JSON.stringify(""));
	};

	closeRefreshing() {
		this.setState({
			isLoading: false,
			refreshing: false
		});
	}
	// 清除筛选条件
	clearFilter = () => {
		this.clearFliterType();
		this.param = {};
		this.paramText = {
			depts: [],
			employee: []
		};
		this.setState(
			{
				dataSource: this.state.dataSource.cloneWithRows([]),
				isLoading: true,
				pageIndex: 1,
				hasMore: false,
				data: [],
				number: 0
			},
			() => {
				this.getLists(1);
			}
		);
	};
	@autobind
	goGrowth(userId) {
		openLink(`?userId=${userId}#/growth`);
	}
	render() {
		console.log("重新刷新");
		let t = this;
		const row = (rowData, sectionID, rowID) => {
			return (
				<div
					className="list-wrap EMPlist"
					onClick={() => {
						window._rlog("_joblist_goGrowth");
						this.goGrowth(rowData.userId);
					}}
				>
					{/* arrow="horizontal" */}
					<Item
						className="on-job-list-item"
						thumb={
							<DDAvatar
								name={rowData.name}
								size=""
								avatar={
									rowData.avatar &&
									mid2Url(rowData.avatar, { imageSize: "thumb" })
								}
								className="growth-avatar-dd-avatar"
								font=""
							/>
						}
						multipleLine
					>
						<h4>
						<span className="name">{rowData.name}</span>
							{/*!rowData.perfectFlag && rowData.employeeStatus !== "4" && (
								<DIcon className="dir-warning-icon" size="xxs" type={require('../../../assets/svg/warning.svg')} />
							)*/}
						</h4>
						<p className="dept">{rowData.mainDeptName}</p>
						<Brief>
							{t.state.currenList == LIST_DEPARTURE &&
								rowData.resignDate && (
									<span>
										<p className="dept">{rowData.deptName}</p>
										<p className="last-date">离职日期：{rowData.resignDate}</p>
									</span>
								)}
							{t.state.currenList != LIST_DEPARTURE &&
								rowData.entryDate && (
									<p className="last-date">入职日期：{rowData.entryDate}</p>
								)}

							{rowData.employeeStatus && (
								<span
									className={`onJob-type onJob-type-${rowData.employeeStatus}`}
								>
									{mapper[rowData.employeeStatus]}
								</span>
							)}
						</Brief>
						<div className="arrow">
							<DIcon type="right" />
						</div>
					</Item>
				</div>
			);
		};

		return (
			<div id="filterContainer">
				<div className="phone-border-fix" />
				{this.state.showFilter && (
					<Filter ref="filter" onFilter={this.onFilter} />
				)}
				<ListView
					ref={el => (this.lv = el)}
					dataSource={this.state.dataSource}
					renderRow={row}
					pageSize={15}
					style={{
						height: this.state.height
					}}
					scrollerOptions={{ scrollbars: true }}
					refreshControl={
						<RefreshControl
							refreshing={this.state.refreshing}
							onRefresh={this.onRefresh}
						/>
					}
					scrollRenderAheadDistance={500}
					scrollEventThrottle={200}
					onEndReached={this.onEndReached}
					onEndReachedThreshold={10}
					renderHeader={() =>
						this.state.showFilter
							? this.renderHeader()
							: this.renderHeaderWithoutFilter()}
				/>
				{this.state.data.length === 0 &&
					this.state.number === 0 &&
					!this.state.isLoading
					? this.renderWithoutData()
					: null}
			</div>
		);
	}

	renderWithoutData() {
		let text = this.getTextByState();
		if (
			this.state.currenList === LIST_PROBATION ||
			this.state.currenList === LIST_DEPARTURE
		) {
			return (
				<div className="on-job-filter-empty">
					<img
						alt=""
						className="on-job-filter-empty-img"
						src="https://gw.alicdn.com/tfs/TB1C2RsmgMPMeJjy1XdXXasrXXa-216-186.png"
					/>
					<p className="on-job-filter-empty-text">当前暂无{text}</p>
				</div>
			);
		} else {
			return (
				<div className="on-job-filter-empty">
					<img
						alt=""
						className="on-job-filter-empty-img"
						src="https://gw.alicdn.com/tfs/TB1v4CrmgMPMeJjy1XcXXXpppXa-216-150.png"
					/>
					<p className="on-job-filter-empty-text">当前暂无筛选结果</p>
				</div>
			);
		}
	}

	createDingMsg() {
		const { fragmentCount } = this.state;
		const corpId = urlParams.getUrlSearchParam("corpId");
		const url = window.location.origin + window.location.pathname + window.location.search + "#/steps";
		dd.biz.ding.create({
			users: fragmentCount, // 用户列表，工号
			corpId, // 企业id
			type: 2, // 附件类型 1：image  2：link
			alertType: 2, // 钉发送方式 0:电话, 1:短信, 2:应用内
			attachment: {
				title: "点击编辑基本信息",
				url: url,
				text: "进入钉钉智能人事维护个人基本信息",
				image: "https://gw.alicdn.com/tfs/TB13u27aOqAXuNjy1XdXXaYcVXa-88-88.png"
			}, // 附件信息
			text: "你的个人资料页缺少重要的基本信息，请马上维护更新", // 正文
			bizType: 0, // 业务类型 0：通知DING；1：任务；2：会议；
			onSuccess: function () {
				//onSuccess将在点击发送之后调用
			},
			onFail: function () { }
		});
	}

	renderHeader() {
		const { fragmentCount } = this.state;
		if (
			this.paramText["depts"].length !== 0 ||
			this.paramText["employee"].length !== 0
		) {
			return (
				<div className="toper-title">
					{
						fragmentCount.length > 0 &&
						<div
							className="tips-board"
							onClick={() => {
								this.createDingMsg();
							}}
						>
							<DIcon className="dir-warning-icon" size="xxs" type={require('../../../assets/svg/warning.svg')} />
							<span>{fragmentCount.length}位员工基本信息不完整</span>
							<span className="fr">提醒员工录入</span>
						</div>
					}
					<div className="on-job-filter-type-label">
						筛选条件:&nbsp;
            			{this.paramText.depts.map((item, i) => {
							return <span key={i}>&nbsp;{item}</span>;
						})}
						{this.paramText.employee.map((item, i) => {
							return <span key={i}>&nbsp;{item}</span>;
						})}
						<span>
							&nbsp;|&nbsp;共{this.state.number}人&nbsp;
              			<span
							className="on-job-filter-type-clear-button"
							onClick={() => this.clearFilter()}
						>
								<Icon type="cross-circle-o" />
							</span>
						</span>
					</div>
				</div>
			);
		} else {
			return (
				<div className="toper-title">
					{
						fragmentCount.length > 0 &&
						<div
							className="tips-board"
							onClick={() => {
								this.createDingMsg();
							}}
						>
							<DIcon className="dir-warning-icon" size="xxs" type={require('../../../assets/svg/warning.svg')} />
							<span>{fragmentCount.length}位员工基本信息不完整</span>
							<span className="fr">提醒员工录入</span>
						</div>
					}
					<div className="on-job-filter-type-label">
						全部在职员工&nbsp;
            			<span>{this.state.number}人&nbsp;&nbsp;</span>
					</div>
				</div>
			);
		}
	}
	renderHeaderWithoutFilter() {
		let text = this.getTextByState();
		if (this.state.data.length === 0 && this.state.number === 0) return null;
		return (
			<div className="on-job-filter-type-label no-mt">
				全部{text}&nbsp;
        <span>{this.state.number}人&nbsp;&nbsp;</span>
			</div>
		);
	}

	getTextByState() {
		let text = "";
		if (this.state.currenList === LIST_PROBATION) {
			text = "试用期员工";
		} else if (this.state.currenList === LIST_DEPARTURE) {
			text = "离职员工";
		} else if (this.state.currenList === LIST_ONJOB) {
			text = "在职员工";
		} else {
			text = "";
		}
		return text;
	}
}
